package hmvc4gwt.framework.client.modul;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.user.client.ui.RootPanel;

import hmvc4gwt.client.component.ComponentSingleChild;
import hmvc4gwt.client.controller.AController;
import hmvc4gwt.client.event.IEvent;
import hmvc4gwt.client.view.IView;
import hmvc4gwt.framework.client.events.AddViewEvent;
import hmvc4gwt.framework.client.events.RemoveViewEvent;

public abstract class ModulController extends AController implements EntryPoint {


	/**
	 * fügt die View zum RootPanel hinzu
	 * @param view
	 */
	private void addView(IView view) {
		
		if (view.getWidget() == null) {
			return;
		}
		
		view.setVisible(true);
		RootPanel.get().add(view.getWidget());
	}
	
	public void init() {
		/*
		 * Controller für das hinzufügen und entfernen von Views registrieren
		 */
		register(AddViewEvent.class, this);
		register(RemoveViewEvent.class, this);
		
		initImpl();
	}

	/**
	 * repräsentiert die Initializeable-Methode doInit()
	 */
	public abstract void initImpl();
	
	public final void handleEvent(IEvent event) {
		
		if (event instanceof AddViewEvent) {
			AddViewEvent addViewEvent = (AddViewEvent) event;
			addView(addViewEvent.getView());
		} else if (event instanceof RemoveViewEvent) {
			RemoveViewEvent removeViewEvent = (RemoveViewEvent) event;
			removeView(removeViewEvent.getView());
		}
		
		
		handleEventImpl(event);
	}
	
	/**
	 * repräsentiert die HmvcListener.handleEvent() Methode
	 */
	public abstract void handleEventImpl(IEvent event);
	
	public void onModuleLoad() {
		new ComponentSingleChild(this);
	}
	
	/**
	 * entfernt die View von der RootPanel
	 * @param view
	 */
	private void removeView(IView view) {
		if (RootPanel.get().remove(view.getWidget())) {
			view.setVisible(false);
		}
	}

}
